package com.yubest.junit.httpserver;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.log4j.lf5.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author: hweiyu
 * @Date: 2024/6/14 10:59
 */
public class ResourcesHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String requestPath = exchange.getRequestURI().getPath();
        if (requestPath.equals("/")) {
            requestPath = "/index.html";
        }
        InputStream is = ResourcesHandler.class.getResourceAsStream("/httpserver" + requestPath);
        if (null != is) {
            byte[] fileBytes = StreamUtils.getBytes(is);
            exchange.getResponseHeaders().add("Content-Type", "text/html");
            exchange.sendResponseHeaders(200, fileBytes.length);
            OutputStream os = exchange.getResponseBody();
            os.write(fileBytes);
            os.close();
        } else {
            exchange.sendResponseHeaders(404, -1);
            OutputStream os = exchange.getResponseBody();
            os.close();
        }
    }
}
